#include <iostream>
#include <fstream>
#include <climits>

#include "archive.h"
#include "path.h"
#include "io.h"

void write_archive(
    std::ostream &os,
    const std::string &dir,
    const Strings &paths,
    const std::string &command)
{
    write_string(os, command);
    unsigned num_files = paths.size();
    write_uint(os, num_files);
    for(int i=0; i<num_files; i++)
    {
        const std::string &rel = paths[i];
        std::string abs = dir + "\\" + rel;
        
        std::ifstream file(abs.c_str(), std::ios::binary);
        unsigned size = file_size(file);
        
        std::cout << rel << "\n";
        
        write_string(os, rel);
        write_uint(os, size);
        copy(file, os);
        file.close();
    }
}

std::string read_archive(
    std::istream &is,
    const std::string &dir)
{
    std::string command = read_string(is);
    unsigned num_files = read_uint(is);
    for(int i=0; i<num_files; i++)
    {
        std::string rel = read_string(is);
        unsigned size = read_uint(is);
        
        std::string abs = dir + "\\" + rel;
        
        ensure_dir_exists(dir_name(abs));
        std::ofstream file(abs.c_str(), std::ios::binary);
        
        copy(is, file, size);
        file.close();
    }
    
    return command;
}
